package com.sqly.doc.menu.grjbxx;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.XListView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 个人基本信息页面--用户列表
 * Created by Administrator on 2017-11-14.
 */

public class jm_list extends MyBaseActivity {


    List<JuMin> list;//信息列表
    XListView listView;
    ZLoadingDialog dialog;//加载动画
    Context con;
    private int pageNum1 = 1;// 无关键字页数
    EditText key;
    //标题
    TextView title, uname;
    LinearLayout back;

    @Override
    protected void initUI() {
        setContentView(R.layout.menu_grjbxx_user_list);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("个人基本信息");
        uname.setText("新增");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(jm_list.this, jm_info_add.class).putExtra("type", "add"));
            }
        });
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        con = jm_list.this;
        key = (EditText) findViewById(R.id.key);
        key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (NetWorkUtils.isNetworkConnected(con)) {
                    getJuminOfNet();
                } else {
//                    getJuminOfLocal();
                    MyToastUtil.ShowToast(con, "联网失败");
                }
            }
        });
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!NetWorkUtils.isNetworkConnected(con)) {//网络没有连接
//            list = DataSupport.findAll(JuMin.class);
//            listView.setPullLoadEnable(false);
//            listView.setPullRefreshEnable(false);
//            listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
//                @Override
//                public void convert(ViewHolder helper, JuMin item) {
//                    helper.setText(R.id.number, DateConvert.dateToString(DateConvert.toDate(item.getCSRQ(), DateConvert.YMD), DateConvert.YMD));
//                    helper.setText(R.id.name, item.getXINGMING());
//                    helper.setText(R.id.cardnum, item.getCARDNUM());
//                }
//            });
            MyToastUtil.ShowToast(con, "联网失败");
        } else {
            getJuminOfNet();
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle b = new Bundle();
                b.putSerializable("b", list.get(i - 1));
                startActivity(new Intent(con, jm_info_add.class).putExtras(b).putExtra("type", "edit"));
            }
        });
    }

    @Override
    protected void initListener() {

    }
    //本地请求居民信息
    public  void getJuminOfLocal(){
        list = DataSupport.where("XINGMING like '%" + key.getText().toString() + "%'").find(JuMin.class);
        listView.setPullLoadEnable(false);
        listView.setPullRefreshEnable(false);
        listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
            @Override
            public void convert(ViewHolder helper, JuMin item) {
                helper.setText(R.id.name, item.getXINGMING());
                helper.setText(R.id.cardnum, item.getCARDNUM());
                helper.setText(R.id.number, DateConvert.dateToString(DateConvert.toDate(item.getCSRQ(), DateConvert.YMD), DateConvert.YMD));
            }
        });
    }
    //网络请求居民信息
    public void getJuminOfNet() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        if (key.getText().toString().length() != 0)
            ps.add("XINGMING", key.getText().toString());
        ps.add("flag", "1");

        UserClient.get(HttpUrl.GetJbxxUserList, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<JuMin> ll = JSON.parseArray(
                            ret.getList(), JuMin.class);
                    if (pageNum1 == 1)
                        list = new ArrayList<JuMin>();
                    for (int i = 0; i < ll.size(); i++) {
                        list.add(ll.get(i));
                    }
                    listView.setSelection(list.size() - ll.size());
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getJuminOfNet();
                        }
                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getJuminOfNet();
                        }
                    });
                    listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
                        @Override
                        public void convert(ViewHolder helper, JuMin item) {
                            helper.setText(R.id.number, DateConvert.dateToString(DateConvert.toDate(item.getCSRQ(), DateConvert.YMD), DateConvert.YMD));
                            helper.setText(R.id.name, item.getXINGMING());
                            helper.setText(R.id.cardnum, item.getJKDAH());
                        }
                    });
                    /**
                    /////////////////////////////////////////////////////////////////////////本地化
                    List<JuMin> dblist = DataSupport.findAll(JuMin.class);
                    if (dblist.size() > 0) {//本地数据没有
                        for (int i = 0; i < ll.size(); i++) {
                            String sfzh = (null ==ll.get(i).getSFZH() || "".equals(ll.get(i).getSFZH())) ? "-1" : ll.get(i).getSFZH();
                            List<JuMin> jlist = DataSupport.where("SFZH = ?", sfzh).find(JuMin.class);
                            if (jlist.size() > 0) {
                                if (jlist.get(0).getIsupdate().equals("1")) {//本地数据没有更新，可以删除添加新的
                                    Log.i("居民数据", "删除后插入的数据");
                                    jlist.get(0).delete();
                                    ll.get(i).setIsupdate("1");//设置不需要更新的操作
                                    ll.get(i).save();
                                } else {//本地有数据保存还没有上传
                                    //不需要任何操作
                                }
                            } else {
                                Log.i("居民数据", "直接插入的数据");
                                ll.get(i).setIsupdate("1");//设置不需要更新的操作
                                ll.get(i).save();
                            }
                        }
                    } else {
                        Log.i("居民数据", "直接插入的数据");
                        for (JuMin j : ll) {
                            j.setIsupdate("1");//设置不需要更新的操作
                            j.save();
                        }
                    }
                    Log.i("目前用户数目：", DataSupport.findAll(JuMin.class).size() + "");
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    */
                } else {
                    MyToastUtil.ShowToast(con, "获取错误");
                }
            }
        });
    }
    /*//网络请求居民信息
    public void getDataList() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        ps.add("flag", "1");

        UserClient.get(HttpUrl.GetSignedUser, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                dialog.dismiss();
                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (pageNum1 == 1)
                        list = new ArrayList<JuMin>();
                    List<JuMin> ll = JSON.parseArray(
                            ret.getList(), JuMin.class);
                    for (int i = 0; i < ll.size(); i++) {
                        list.add(ll.get(i));
                    }
                    listView.setSelection(list.size() - ll.size());
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getDataList();
                        }

                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getDataList();
                        }
                    });
                    listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
                        @Override
                        public void convert(ViewHolder helper, JuMin item) {
                            helper.setText(R.id.number, item.getJKDAH());
                            helper.setText(R.id.name, item.getXINGMING());
                        }
                    });
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Bundle b=new Bundle();
                            b.putSerializable("b",list.get(i));
                            startActivity(new Intent(con,jm_info_add.class).putExtras(b));
                        }
                    });

                } else {
                    MyToastUtil.ShowToast(con, "获取错误");
                }

            }
        });
    }*/
}
